<template>
  <el-dialog :title="title" v-model="visible" class="dialog-sm" append-to-body @close="visible = false">
    <el-form ref="formRef" :model="form" :rules="rules" label-width="80px" v-loading="loading">
      <el-form-item label="字典名称" prop="name">
        <el-input v-model="form.name" placeholder="请输入字典名称" />
      </el-form-item>
      <el-form-item label="字典类型" prop="type">
        <el-input v-model="form.type" placeholder="请输入字典类型" />
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button class="medium" type="primary" :loading="submitting" :disabled="loading" @click="handleSubmit"
          >确 定</el-button
        >
        <el-button class="medium" @click="visible = false">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup name="DictForm">
  import { infoTypeApi, addTypeApi, editTypeApi } from '@/api/system/dict/type'

  const props = defineProps({ row: Object, moduleName: String })
  const visible = defineModel()
  const { proxy } = getCurrentInstance()

  const data = reactive({
    title: '',
    loading: false,
    submitting: false,
    form: {
      name: undefined,
      type: undefined,
      remark: undefined
    },
    rules: {
      name: [{ required: true, message: '字典名称不能为空', trigger: 'blur' }],
      type: [{ required: true, message: '字典类型不能为空', trigger: 'blur' }]
    }
  })
  const { title, loading, submitting, form, rules } = toRefs(data)
  const emit = defineEmits(['submit'])

  // 初始化加载
  onMounted(async () => {
    loading.value = true
    form.value.id = props.row?.id || undefined
    if (form.value.id) {
      title.value = '编辑' + props.moduleName
      await getRowData()
    } else {
      title.value = '添加' + props.moduleName
    }
    loading.value = false
  })

  // 获取数据
  async function getRowData() {
    try {
      const { info } = await infoTypeApi(form.value.id)
      form.value = proxy.dataToForm(form.value, info)
    } catch (error) {
      visible.value = false
    }
  }

  // 提交保存
  const formRef = useTemplateRef('formRef')
  async function handleSubmit() {
    try {
      const valid = await formRef.value.validate()
      if (!valid) return
    } catch (error) {
      return
    }
    if (submitting.value) return
    submitting.value = true
    try {
      await proxy.$modal.confirm('确定提交表单数据？')
      if (form.value.id) {
        await editTypeApi(form.value)
      } else {
        await addTypeApi(form.value)
      }
      emit('submit')
      proxy.$modal.msgSuccess('操作成功')
      visible.value = false
    } catch (e) {
      submitting.value = false
    }
  }
</script>
